package controllers.wx;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.tom.basic.service.ServiceQueryResult;
import com.tom.basic.service.ServiceResult;
import com.tom.basic.utils.XTimeUtils;
import controllers.filter.FilterPortal;
import models.*;
import models.services.KeJianService;
import models.services.QuestionAnswerService;
import models.services.SubjectDictionaryService;
import models.services.UserHistoryService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import play.mvc.Controller;
import play.mvc.With;
import support.*;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@With(FilterPortal.class)
public class WeiXinPortal extends Controller {

    public static void appData(Long bigCateId) {
        if (bigCateId == null) {
            renderJSON(ServiceResult.asSuccess(new IndexDataVO(Lists.newArrayList())));
        }
        BigCate bigCate = BigCate.findById(bigCateId);
        List<AppBanner> banners = bigCate.bannerUrlsShow();
        IndexDataVO result = new IndexDataVO(banners);
        if (bigCateId != null) {
            result.videos = VideoIndex.find("isDelete = 0 and bigCateId=:bigCateId order by sortOrder desc ").setParameter("bigCateId",
                    bigCateId).fetch(10);
        }

        // 给这个用户弄个试题库
        String openId = request.headers.get("accesstoken") != null ? request.headers.get("accesstoken").value() : "";
        UserTDTiMu.init(openId, bigCateId);
        renderJSON(ServiceResult.asSuccess(result).toJson(VideoIndex.class));
    }

    /**
     * 查询首页的数据
     *
     * @param bigCateId
     */
    public static void getSubJectData(Long bigCateId) {
        if (bigCateId == null) {
            renderJSON(ServiceQueryResult.asSuccess(Lists.newArrayList()));
        }
        List<SubjectDictionary> subjectDictionaries = SubjectDictionaryService.querySubDict(bigCateId);
        Map<Long, Long> qaItemCount =
                SubjectDictionaryService.countSubQas(subjectDictionaries.stream().map(e -> e.id).collect(Collectors.toList()));
        subjectDictionaries.forEach(e -> e.qaCount = qaItemCount.get(e.id));
        String openId = request.headers.get("accesstoken") != null ? request.headers.get("accesstoken").value() : "";
        if (StringUtils.isNotBlank(openId)) {
            Map<Long, Long> subjectCount = UserHistoryService.getUserHadTestData(openId);
            subjectDictionaries.forEach(e -> {
                Long count = subjectCount.get(e.id);
                if (count == null) {
                    count = 0L;
                }
                if (e.qaCount == null || e.qaCount == 0L) {
                } else {
                    e.percent = Long.parseLong(String.format("%.0f", count * 100 / e.qaCount * 1.0f));
                }
            });
        }
        renderJSON(ServiceQueryResult.asSuccess(subjectDictionaries).toJson());
    }


    /**
     * 查询sub页面的数据
     *
     * @param subjectId
     */
    public static void getChildData(Long subjectId) {
        if (subjectId == null) {
            renderJSON(ServiceQueryResult.asSuccess(Lists.newArrayList()));
        }
        List<ChildSubjectDictionary> childSubjectDictionaries =
                ChildSubjectDictionary.find("isDelete = 0 and parentId=:parentId order " + "by" + " " + "sortOrder desc").setParameter(
                        "parentId", subjectId).fetch();
        Map<Long, Long> qaItemCount =
                SubjectDictionaryService.countChildQas(childSubjectDictionaries.stream().map(e -> e.id).collect(Collectors.toList()));
        childSubjectDictionaries.forEach(e -> {
            e.qaCount = qaItemCount.get(e.id);
        });
        String openId = request.headers.get("accesstoken") != null ? request.headers.get("accesstoken").value() : "";
        if (StringUtils.isNotBlank(openId)) {
            Map<Long, Long> childDataCount = UserHistoryService.getUserHadTestSubData(subjectId, openId);
            childSubjectDictionaries.forEach(e -> {
                Long count = childDataCount.get(e.id);
                if (count == null) {
                    count = 0L;
                }
                if (e.qaCount == null || e.qaCount == 0L) {
                } else {
                    e.percent = Long.parseLong(String.format("%.0f", count * 100 / e.qaCount * 1.0f));
                }
            });
        }


        renderJSON(ServiceQueryResult.asSuccess(childSubjectDictionaries).toJson());
    }

    /**
     * @param childId
     */
    public static void getQa(Long childId) {
        if (childId == null) {
            renderJSON(ServiceQueryResult.asSuccess(Lists.newArrayList()));
        }
        WeiXinUser user = FilterPortal.getUser();
        ServiceQueryResult<QuestionAnswer> resData = QuestionAnswerService.queryData(null, null, null, childId, 1, 1000);
        if (user != null) {
            List<UserCollect> collects = UserCollect.find("isDelete = 0 and openId=:openId").setParameter("openId", user.openId).fetch();
            List<Long> collectQaIds = collects.stream().map(e -> e.qaId).collect(Collectors.toList());
            resData.obj.forEach(e -> e.isUserCollect = collectQaIds.contains(e.id));
        }
        renderJSON(resData.toJson());
    }

    /**
     * (取消)收藏某一个题目
     *
     * @param qaId
     */
    public static void starQa(Long qaId) {
        if (qaId == null) {
            renderJSON(ServiceResult.asFail("参数错误"));
        }
        WeiXinUser user = FilterPortal.getUser();
        UserCollect collect = UserCollect.find("isDelete = 0 and qaId=:qaId").setParameter("qaId", qaId).first();
        if (collect != null) {
            collect.isDelete = 1;
            collect.save();
            renderJSON(ServiceResult.asFail("取消收藏"));
        } else {
            collect = new UserCollect();
        }
        QuestionAnswer qa = QuestionAnswer.findById(qaId);
        if (qa == null) {
            renderJSON(ServiceResult.asFail("参数错误"));
        }
        collect.bigCateId = qa.bigCateId;
        collect.childCateId = qa.childCateId;
        collect.subCateId = qa.subCateId;
        collect.openId = user.openId;
        collect.qaId = qaId;
        collect.save();
        renderJSON(ServiceResult.asSuccess(collect));
    }


    /**
     * 提交一个题目
     *
     * @param qaId
     * @param userSelect
     */
    public static void confirmQa(Long qaId, String userSelect, boolean isDayTest) {
        if (qaId == null) {
            renderJSON(ServiceResult.asFail("参数错误"));
        }
        QuestionAnswer qa = QuestionAnswer.findById(qaId);
        if (qa == null) {
            renderJSON(ServiceResult.asFail("参数错误"));
        }
        JSON qaAnswerData = JSONUtil.parse(qa.selectAbleData); // 题目的答案
        JSONArray array = (JSONArray) qaAnswerData;
        List<String> rightAnswer = Lists.newArrayList();
        for (int i = 0; i < array.size(); i++) {
            Object e = array.get(i);
            JSONObject object = JSONUtil.parseObj(e);
            Boolean isAnswer = object.getBool("isAnswer");
            if (isAnswer != null && isAnswer) {
                String x = String.valueOf((char) (i + 65));
                rightAnswer.add(x);
            }
        }
        String res = Joiner.on(",").join(rightAnswer);
        boolean isRight = true;
        if (!res.equalsIgnoreCase(userSelect)) {
            // 错题
            isRight = false;
        }

        WeiXinUser user = FilterPortal.getUser();
        UserHistory history = UserHistory.find("isDelete = 0 and qaId=:qaId").setParameter("qaId", qaId).first(); // 如果已经有了，先删掉
        if (history != null) {
            history.isDelete = 1;
            history.save();
        }
        history = new UserHistory();
        history.childCateId = qa.childCateId;
        history.bigCateId = qa.bigCateId;
        history.subCateId = qa.subCateId;
        history.openId = user.openId;
        history.qaId = qaId;
        if(isDayTest){
            history.dayTestDate = XTimeUtils.formatDate(new Date(), "yyyy-MM-dd");
        }
        history.isCorrect = isRight;
        history.save();
        renderJSON(ServiceResult.asSuccess(history));
    }

    /**
     * 获取我的历史记录数据
     */
    public static void getMyHistory(Long bigCateId) {
        WeiXinUser user = FilterPortal.getUser();
        List<UserHistory> history =
                UserHistory.find("isDelete = 0 and openId=:openId and bigCateId=:bigCateId order by id desc").setParameter("bigCateId",
                        bigCateId).setParameter("openId", user.openId).fetch(100);
        List<Long> ids = history.stream().map(e -> e.qaId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(ids)) {
            renderJSON(ServiceQueryResult.asSuccess(Lists.newArrayList()));
        }
        List<QuestionAnswer> questionAnswers = QuestionAnswer.find("isDelete = 0 and id in(:ids)").setParameter("ids", ids).fetch();
        Map<Long, QuestionAnswer> questionAnswerMap = questionAnswers.stream().collect(Collectors.toMap(e -> e.id, e -> e));
        List<QuestionAnswer> result = Lists.newArrayList();
        history.forEach(e -> {
            QuestionAnswer questionAnswer = questionAnswerMap.get(e.qaId);
            if (questionAnswer != null) {
                result.add(questionAnswer);
            }
        });
        if (user != null) {
            List<UserCollect> collects = UserCollect.find("isDelete = 0 and openId=:openId").setParameter("openId", user.openId).fetch();
            List<Long> collectQaIds = collects.stream().map(e -> e.qaId).collect(Collectors.toList());
            result.forEach(e -> e.isUserCollect = collectQaIds.contains(e.id));
        }
        ServiceQueryResult<QuestionAnswer> res = new ServiceQueryResult();
        res.totalCount = result.size();
        res.obj = result;
        renderJSON(res.toJson());
    }


    /**
     * 获取我的错题
     */
    public static void getMyWrong(Long bigCateId) {
        WeiXinUser user = FilterPortal.getUser();
        List<UserHistory> history =
                UserHistory.find("isDelete = 0 and isCorrect = 0 and openId=:openId and bigCateId=:bigCateId order " + "by" + " id desc").setParameter("bigCateId", bigCateId).setParameter("openId", user.openId).fetch(100);
        List<Long> ids = history.stream().map(e -> e.qaId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(ids)) {
            renderJSON(ServiceQueryResult.asSuccess(Lists.newArrayList()));
        }
        List<QuestionAnswer> questionAnswers = QuestionAnswer.find("isDelete = 0 and id in(:ids)").setParameter("ids", ids).fetch();
        Map<Long, QuestionAnswer> questionAnswerMap = questionAnswers.stream().collect(Collectors.toMap(e -> e.id, e -> e));
        List<QuestionAnswer> result = Lists.newArrayList();
        history.forEach(e -> {
            QuestionAnswer questionAnswer = questionAnswerMap.get(e.qaId);
            if (questionAnswer != null) {
                result.add(questionAnswer);
            }
        });
        if (user != null) {
            List<UserCollect> collects = UserCollect.find("isDelete = 0 and openId=:openId").setParameter("openId", user.openId).fetch();
            List<Long> collectQaIds = collects.stream().map(e -> e.qaId).collect(Collectors.toList());
            result.forEach(e -> e.isUserCollect = collectQaIds.contains(e.id));
        }
        ServiceQueryResult<QuestionAnswer> res = new ServiceQueryResult();
        res.totalCount = result.size();
        res.obj = result;
        renderJSON(res.toJson());
    }


    /**
     * 获取我的收藏
     */
    public static void getMyCollect(Long bigCateId) {
        WeiXinUser user = FilterPortal.getUser();
        List<UserCollect> collects =
                UserCollect.find("isDelete = 0 and openId=:openId and bigCateId=:bigCateId order by id desc").setParameter("bigCateId",
                        bigCateId).setParameter("openId", user.openId).fetch();
        List<Long> ids = collects.stream().map(e -> e.qaId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(ids)) {
            renderJSON(ServiceQueryResult.asSuccess(Lists.newArrayList()));
        }
        List<QuestionAnswer> questionAnswers = QuestionAnswer.find("isDelete = 0 and id in(:ids)").setParameter("ids", ids).fetch();
        Map<Long, QuestionAnswer> questionAnswerMap = questionAnswers.stream().collect(Collectors.toMap(e -> e.id, e -> e));
        List<QuestionAnswer> result = Lists.newArrayList();
        collects.forEach(e -> {
            QuestionAnswer questionAnswer = questionAnswerMap.get(e.qaId);
            if (questionAnswer != null) {
                result.add(questionAnswer);
            }
        });
        result.forEach(e -> e.isUserCollect = true);
        ServiceQueryResult<QuestionAnswer> res = new ServiceQueryResult();
        res.totalCount = result.size();
        res.obj = result;
        renderJSON(res.toJson());
    }


    public static void shuaTiLv(Long bigCateId) {
        String openId = request.headers.get("accesstoken") != null ? request.headers.get("accesstoken").value() : "";
        long allCount = UserHistory.count("isDelete = 0 and openId='" + openId + "' and bigCateId=" + bigCateId);
        long rightCount = UserHistory.count("isDelete = 0 and openId='" + openId + "' and isCorrect = 1 and bigCateId=" + bigCateId);
        AnswerTongJi tongJi = new AnswerTongJi();
        tongJi.allCount = allCount;
        tongJi.rightCount = rightCount;
        if (allCount != 0) {
            tongJi.successPercent = rightCount * 100 / allCount;
        }
        renderJSON(ServiceResult.asSuccess(tongJi));
    }


    public static void getMyDayTest(Long bigCateId) {
        if (bigCateId == null) {
            renderJSON(ServiceQueryResult.asSuccess(Lists.newArrayList()));
        }
        WeiXinUser user = FilterPortal.getUser();
        List<UserCollect> collects =
                UserCollect.find("isDelete = 0 and openId=:openId and bigCateId=:bigCateId order by id desc").setParameter("bigCateId",
                        bigCateId).setParameter("openId", user.openId).fetch();
        List<Long> collectIds = collects.stream().map(e -> e.qaId).collect(Collectors.toList());
        List<QuestionAnswer> questionAnswers = UserTDTiMu.getQaIds(user.openId, bigCateId);
        questionAnswers.forEach(e -> e.isUserCollect = collectIds.contains(e.id));
        ServiceQueryResult<QuestionAnswer> res = new ServiceQueryResult();
        res.totalCount = questionAnswers.size();
        res.obj = questionAnswers;
        renderJSON(res.toJson());
    }


    public static void getUserDayTestTongJi(Long bigCateId) {
        DayResultVo resultVo = new DayResultVo();
        WeiXinUser user = FilterPortal.getUser();
        String dayTestDate = XTimeUtils.formatDate(new Date(), "yyyy-MM-dd");
        List<UserHistory> userHistories = UserHistory.find("isDelete = 0 and openId=:openId and dayTestDate=:dayTestDate and bigCateId = "
                        + bigCateId).setParameter("openId", user.openId)
                .setParameter("dayTestDate", dayTestDate).fetch();
        resultVo.total = UserTDTiMu.getQaIds(user.openId, bigCateId).size();
        resultVo.success = userHistories.stream().filter(e -> e.isCorrect).count();
        resultVo.successLv = (long) ((resultVo.total == 0 ? 0 : resultVo.success * 1.0f / resultVo.total) * 100);
        renderJSON(ServiceResult.asSuccess(resultVo));
    }


    public static void queryKeJian(Long cateId) {
        if (cateId == null) {
            renderJSON(ServiceQueryResult.asSuccess(Lists.newArrayList()));
        }
        ServiceQueryResult<KeJian> resData = KeJianService.queryData(null, cateId, 1, 100);
        renderJSON(resData.toJson(KeJian.class));
    }


    public static void queryKeJianCate(Long bigCateId) {
        if (bigCateId == null) {
            renderJSON(ServiceQueryResult.asSuccess(Lists.newArrayList()));
        }
        String sql = "isDelete = 0 ";
        sql += " and bigCateId=" + bigCateId;
        List<KeJianCategory> keJianCategories = KeJianCategory.find(sql + " order by sortOrder desc").fetch();
        renderJSON(ServiceQueryResult.asSuccess(keJianCategories).toJson(KeJianCategory.class));
    }


//    public static void prePay(String openId, String ){
//        WxPayUnifiedOrderV3Request orderRequest = new WxPayUnifiedOrderV3Request();
//        orderRequest.setOutTradeNo(record.payNo);// 商户订单号
//        orderRequest.setAppid(NgWxPayService.APP_ID);
//        orderRequest.setDescription("Express No:" + order.expressNo);
//        orderRequest.setNotifyUrl("https://ng-express.kikuu.com/WeixinController/payNotify");
//        WxPayUnifiedOrderV3Request.Payer payer = new WxPayUnifiedOrderV3Request.Payer();
//        payer.setOpenid(openId);
//        orderRequest.setPayer(payer);
//        // 元转成分
//        int fee = 0;
//        BigDecimal actualPrice = new BigDecimal("0.01");
//        if (!BizConstants.isInProduct()) {
//            actualPrice = amountCNY;
//        }
//        fee = actualPrice.multiply(new BigDecimal(100)).intValue();
//        WxPayUnifiedOrderV3Request.Amount amountRequest = new WxPayUnifiedOrderV3Request.Amount();
//        amountRequest.setCurrency("CNY");
//        amountRequest.setTotal(fee);
//        orderRequest.setAmount(amountRequest);
//        WxPayUnifiedOrderV3Result.JsapiResult result =
//                NgWxPayService.getWxPayService(TradeTypeEnum.JSAPI).createOrderV3(TradeTypeEnum.JSAPI, orderRequest);
//    }
}
